from flask import request, g
from flask_restful import abort

from apps.models.user import User
from exts import cache


def check_user():
    auth = request.headers.get('Authorization')
    if not auth:
        abort(401, msg='请先登陆')
    name = cache.get(auth)

    if not name:
        abort(401, msg='无效令牌')
    user = User.query.filter(User.username == name)
    g.user = user


def login_required(func):
    def wrapper(*args, **kwargs):
        check_user()
        return func(*args, **kwargs)

    return wrapper
